import 'package:lcapp/basic/local_info.dart';
import 'package:lcapp/model/db/sql_constant.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

class SqliteSingleton {
  static SqliteSingleton _sqliteSingleton = SqliteSingleton._();
  SqliteSingleton._();
  static SqliteSingleton getInstance() {
    return _sqliteSingleton;
  }

  Future<Database> getBaseDB() async {
    return await getDatabase(BASE_DB_FOLDER_NAME, BASE_DB_NAME);
  }

  Future<Database> getUserDB() async {
    return await getDatabase(AsrLocalInfo.userId.toString(), DB_NAME);
  }

  ///获取database实例，
  Future<Database> getDatabase(String phone, String dbName) async {
    List createSql = [];
    if (dbName == BASE_DB_NAME) {
      createSql = SqlConstants.createTableBase;
    } else if (dbName == DB_NAME) {
      createSql = SqlConstants.createTable;
    }
    Database database = await createDatabase(phone, dbName, createSql);
    return database;
  }

  ///创建数据库
  Future<Database> createDatabase(
      String phone, String dbName, List createSql) async {
    String databasePath = await getDatabasesPath();
    String path = join(databasePath, phone + '/' + dbName);
    Database database = await openDatabase(path, version: 7,
        onCreate: (Database db, int version) async {
      for (var sql in createSql) {
        await db.execute(sql);
      }
    }, onUpgrade: (Database db, int oldVersion, int newVersion) async {
      for (var sql in createSql) {
        await db.execute(sql);
      }
    });
    return database;
  }

}
